<template>
  <main class="container text-white">
    <div class="pt-4 mb-8 relative">
      <input
        type="text"
        placeholder="请输入城市名称"
        class="py-2 px-1 w-full bg-weather border-b focus:border-weather-secondary focus:outline-none focus:shadow-md"
        v-model="cityName"
      />
      <ul
        class="bg-weather-secondary text-white w-full shadow-md py-2 px-1 top-[62px]"
        v-if="cityName !== ''"
      >
        <router-link
          :to="'/weather/' + cityAdcode + '?search=' + citySearch[0].city"
        >
          <p v-if="cityInfo[0] === 'OK'">{{ citySearch[0].city }}</p>
        </router-link>
        <p v-if="cityInfo[0] === 'undefined'">
          对不起网络似乎除了点问题 请稍后再查询
        </p>
        <p v-if="cityInfo[0] === 'ENGINE_RESPONSE_DATA_ERROR'">
          似乎没有找到你查找的城市
        </p>
      </ul>
    </div>
    <h2 class="text-center duration-200" v-if="Number(len) === 0" >
      暂时没有保存过城市天气信息，请查询后点击右上角"+"号保存。
    </h2>
   <div v-if="Number(len) > 0">
    <div class="group/item flex justify-between" v-for="(item, index) in constKey"
        :key="index">
      <div
        class="mb-4 bg-weathers py-2 px-4 flex justify-between cursor-pointer w-full group-hover/item:w-4/5 duration-300"
      >
        <h3>{{ item[0] }}</h3>
        <span>{{ item[1] }}</span>
      </div>
      <div class="mb-4 gap-2 hidden group-hover/item:flex" >
        <button class="bg-yellow text-center w-[80px]" @click="handleRead(item[0])">查看</button
        ><button class="bg-yellow text-center w-[80px]" @click="handleDelete(item[0],index)">删除</button>
      </div>
    </div>
  </div>
    <h2 class="mt-6">近期天气</h2>
    <div class="bg-weathers px-12 pt-10 mt-2 rounded">
      <div class="flex gap-6">
        <div
          class="flex flex-col flex-1 text-center gap-4"
          v-for="(item, index) in tonowAddress"
          :key="index"
        >
          <span>{{ item.week }}</span
          ><span
            >{{ item.date.split('-')[1] }}-{{ item.date.split('-')[2] }}</span
          ><span>{{ item.dayweather }}</span
          ><span>风力 {{ item.daypower }}级</span>
        </div>
      </div>
      <div class="h-40 mt-10">
        <v-chart :option="option" />
      </div>
    </div>
  </main>
</template>

<script>
import Vue from 'vue';
import axios from 'axios';
import { RouterLink } from 'vue-router';
import { getNowAddress } from '@/api/index.js';
export default {
  data() {
    return {
      option: {},
      weekDay: ['周日', '周一', '周二', '周三', '周四', '周五', '周六'],
      tonowAddress: [],
      daytemp: [],
      nighttemp: [],
      cityName: '',
      citySearch: [],
      cityInfo: [],
      cityAdcode: '',
      isShow: false,
      len:'',
      constKey: [],
    };
  },
  methods: {
    handleClick(data1, data2) {
      this.option = {
        xAxis: {
          type: 'category',
          show: false,
          data: ['Mon', 'Tue', 'Wed', 'Thu'],
        },
        yAxis: {
          type: 'value',
          show: false,
          
        },
        legend: {
          show: false,
        },
        series: [
          
          {
            data: data1,
            type: 'line',
  
            smooth: true,
            label: {
              show: 'true',
              position: 'top',
              color: '#fff',
              formatter: function (data) {
                return '白' + data.value + '°C';
              },
            },
          },
          {
            data: data2,
            type: 'line',
            smooth: true,
            label: {
              show: 'true',
              position: 'bottom',
              color: '#fff',
              formatter: function (data) {
                return '晚' + data.value + '°C';
              },
            },
          },
        ],
      };
    },
    handleSearch(city) {
      const url = `https://restapi.amap.com/v3/geocode/geo?address=${city}&key=a9f817f97dc77012f714e1534dd24fb1`;
      axios.get(url).then((res) => {
        this.cityInfo = [];
        this.citySearch = [];
        this.cityAdcode = '';
        this.citySearch.push(res.data.geocodes[0]);
        this.cityInfo.push(res.data.info);
        this.cityAdcode = this.citySearch[0].adcode;
        console.log(this.cityAdcode);
        console.log(this.citySearch[0].city);
        console.log(this.cityInfo, 'cityInfo');

      });
    },
    handleDelete(key,index) {
      localStorage.removeItem(key);
      this.constKey.splice(index, 1);
      this.len = Number(this.len) - 1;
      console.log(this.len,'len')
      console.log(this.constKey.length,'constKey')
    },
    handleRead(key) {
      console.log(key,'key16516')
      const url = `https://restapi.amap.com/v3/geocode/geo?address=${key}&key=a9f817f97dc77012f714e1534dd24fb1`
      axios.get(url).then((res) => {
        const item = res.data.geocodes[0].adcode+'?search='+key;
        this.$router.push({
        path: `/weather/${item}`,
      })
      })
    },
  },
  async mounted() {
    const nowaddress = await getNowAddress();
    const res = nowaddress.data.forecasts[0].casts;
     this.len =localStorage.length;
    console.log(this.len)
    const keys = [];
    for (let i = 0; i < Number(this.len); i++) {
      keys.push(localStorage.key(i));
    }
    keys.forEach((item) => {
      const degs = localStorage.getItem(item);
      const url = `https://restapi.amap.com/v3/weather/weatherInfo?city=${degs}&key=a9f817f97dc77012f714e1534dd24fb1&extensions=base`;
      axios.get(url).then((res) => {
        const data = res.data.lives[0].temperature;
        console.log(data,'data')
        this.constKey.push([item,data+'度'])
      })
      console.log(degs)
    })
    res.forEach((item) => {
      const day = new Date();
      const index = day.getDay();
      if (Number(item.week) === index) {
        item.week = '今天';
      } else if (Number(item.week) === index + 1) {
        item.week = '明天';
      }else if(Number(item.week) === 7){
            item.week = '周日'
          } else {
        item.week = this.weekDay[Number(item.week)];
      }
      this.tonowAddress.push(item);
      this.daytemp.push(item.daytemp);
      this.nighttemp.push(item.nighttemp);
    });
    Vue.delete(this.daytemp, '__ob__');
    Vue.delete(this.nighttemp, '__ob__');
    console.log(this.daytemp);
    console.log(this.nighttemp);
    this.handleClick(this.daytemp, this.nighttemp);
  },
  watch: {
    cityName(val) {
      
      this.handleSearch(val);
    },

  },
};
</script>
